<?php

namespace Beerus\Modules\DesignerAuth\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use App\Http\Controllers\Controller;
use Doraemon\cache\Queue;
use Doraemon\model\BlackList;
use Doraemon\model\Designer;
use Doraemon\model\DesignerAuth;
use Doraemon\model\DesignerOrder;
use Doraemon\model\DesignerPayService;
use Doraemon\model\Member;
use Doraemon\model\Phone;
use Doraemon\service\BusinessUser\EncryptPhone;
use Doraemon\service\Designer\AuthService;
use Doraemon\service\Designer\DesignerDingTalkAlert;
use Doraemon\service\Designer\DesignerEquityService;
use Doraemon\service\Designer\DesignerService;
use Doraemon\service\DingTalkAlert;
use Doraemon\service\Member\PhoneCrypto;
use Doraemon\service\search\DesignerSearch;
use Doraemon\service\User;
use Doraemon\service\WechatAlert;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\HhzNiceLivingUrl;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\Sms;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use hhz\constant\basic\UserExtendPhoneScene;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class DesignerPayServiceController extends Controller
{
	const PAGE_SIZE = 30;

    // 可操作人员限制(开通认证等)
    const OPERATOR_LIST = [
        'liziyan',
        'yangxuwen',
        'hanlifan',
        'lishuai',
        'lijiaqi1',
    ];

	public function __construct()
	{
		parent::__construct();
		Admin::script('$(".pjax-container").attr("id","pjax-container");');
	}

	public function index(Request $request, Content $content, $uid = 0)
	{
		if ((HhzEnv::isProduction() || HhzEnv::isGray()) && !in_array(Admin::user()->username, self::OPERATOR_LIST)) {
			$error = new MessageBag([
				'title' => '您没有权限操作'
			]);

			return back()->withInput()->with(compact('error'));
		}

		$orders = DesignerOrder::select('*', [
			'uid' => $uid,
			'pay_status' => DesignerOrder::PAY_STATUS_PAID
		]);

		// 查询当前用户所有订单的服务开通情况
		$services = DesignerPayService::select('*', [
			'uid' => $uid
		]);
		$services = is_array($services) ? $services : [];

		$map_order_service = [];
		foreach ($services as $service) {
			$dsn = trim($service['dsn']);
			$map_order_service[$dsn] = $service;
		}

		foreach ($orders as &$item) {
			$item['order_status_text'] = DesignerOrder::ORDER_STATUS[$item['order_status']];
			$item['pay_platform'] = DesignerOrder::PAY_PLATFORM[$item['pay_platform']];
			$item['pay_status_text'] = DesignerOrder::PAY_STATUS[$item['pay_status']];
			$item['settle_status'] = DesignerOrder::SETTLE_STATUS[$item['settle_status']];
			$item['refund_status_text'] = DesignerOrder::REFUND_STATUS[$item['refund_status']];

			$item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
			$item['pay_time'] = empty($item['pay_time']) ? '-' : date('Y-m-d H:i:s', $item['pay_time']);
			$item['settle_time'] = empty($item['settle_time']) ? '-' : date('Y-m-d H:i:s', $item['settle_time']);
			$item['refund_time'] = empty($item['refund_time']) ? '-' : date('Y-m-d H:i:s', $item['refund_time']);
			$dsn = trim($item['dsn']);
			$item['is_new_order'] = empty($map_order_service[$dsn]);
		}
		unset($item);

		$total = count($orders);
		$gridModel = new pGridDataModel($orders, $total, [
			'perPage' => self::PAGE_SIZE
		]);
		$gridList = Admin::grid(
			$gridModel,
			function (Grid $grid) use ($gridModel) {
				$grid->paginate($gridModel->getPerPage());
				$grid->disableExport();
				$grid->disableRowSelector();
				$grid->disableCreateButton();
				$grid->disableFilter();

				$grid->column('uid', 'UID')->width(100);
				$grid->column('nick', '昵称');
				$grid->column('dsn', '设计师订单号')->width(120);
				$grid->column('package_id', '服务套餐商品id')->width(150);
				$grid->column('package_name', '服务套餐商品名称')->width(150);
				$grid->column('create_time', '下单时间')->width(100);
				$grid->column('order_status_text', '订单状态')->width(100);
				$grid->column('pay_platform', '支付方式')->width(120);
				$grid->column('other_sn', '第三方订单号')->width(150);
				$grid->column('pay_time', '支付时间')->width(100);
				$grid->column('pay_status_text', '支付状态')->width(100);
				$grid->column('amount', '实付金额')->width(100);
				$grid->column('price', '订单金额')->width(100);
				$grid->column('product_price', '商品金额')->width(100);
				$grid->column('settle_status', '结算状态')->width(100);
				$grid->column('settle_time', '结算时间')->width(100);
				$grid->column('refund_status_text', '退款状态')->width(100);
				$grid->column('refund_time', '退款时间')->width(100);

				$grid->actions(function (Grid\Displayers\Actions $actions) {
					$actions->disableDelete();
					$actions->disableView();
					$actions->disableEdit();
					if ($actions->row->is_new_order && $actions->row->refund_status == 1) {
						$actions->append("<a href=\"/admin/DesignerAuth/open_service/" .
							$actions->row->dsn . "/{$actions->row->uid}\" class=\"btn btn-primary\" style='margin-bottom: 5px'><i class=\"fa fa-check\">&nbsp;开通服务</i></a>");
					}
				});
			}
		);

		return $content
			->header('设计师认证服务开通')
			->breadcrumb([
				'text' => '待开通认证',
				'url' => route('list', ['tab' => 2])
			], [
				'text' => '设计师认证服务开通'
			])
			->row($gridList->render());
	}

	// 开通认证服务
	public function openService($dsn, $uid)
	{
		$auth_info = DesignerAuth::getByUId($uid);
		//处理手机号加密业务
        $authPhone = EncryptPhone::getDecryptPhoneInfo($auth_info['encrypt_phone_id'],UserExtendPhoneScene::DESIGNER_AUTH_PHONE);
		$designer_type = (int)$auth_info['designer_type'];

		// 再次确认案例、资料是否审核通过，是否缴费
		if ($auth_info['house_article_audit_status'] != DesignerAuth::STATUS_AUDIT_PASS ||
			$auth_info['identity_info_audit_status'] != DesignerAuth::STATUS_AUDIT_PASS ||
			$auth_info['is_pay'] != DesignerAuth::HAVE_PAID) {
			$error = new MessageBag([
				'title' => '请检查用户案例、资料是否通过审核，以及是否缴费'
			]);

			return back()->withInput()->with(compact('error'));
		}

		$admin_id = Admin::user()->id;

		$name = '';
		if ($designer_type === DesignerAuth::DESIGNER_TYPE_COMPANY_EMPLOYEE) {
			$name = empty($auth_info['company_name']) ? '' : trim($auth_info['company_name']);
		} elseif ($designer_type === DesignerAuth::DESIGNER_TYPE_COMPANY) {
			$name = $auth_info['enterprise_name'];
		}

		$params = [
			'type' => Member::AUTH_USER_DESIGNER,
			'phone' => $authPhone,
			'show_phone' => 9,
			'remark' => '',
			'adm_is_recommend' => 1,
			'brand_name' => '',
			'designer_type' => $designer_type,
			'identity_contain' => '',
			'name' => $name,
			'reg_number' => '',
			'manager_scope_normal' => '',
			'manager_scope_pre' => '',
			'company_type' => '',
			'establish_time' => 0,
			'business_time' => 0,
		];

		// 查询当前订单是否为免费套餐
		$res = DesignerService::openService($dsn, Member::AUTH_USER_DESIGNER, $admin_id, $params);

		if ($res) {
			// 服务开启成功后更新用户状态为"已认证"
			$update_data = [
				'auth_status' => DesignerAuth::STATUS_AUTH_COMPLETE,
				'admin_id' => Admin::user()->id,
				'admin_name' => $_SESSION['name'],
				'plan_type' => DesignerAuth::PLAN_TYPE_COMMON,
				'is_pay' => DesignerAuth::HAVE_PAID,
				'operate_time' => time(),
			];
			DesignerAuth::updateInfo($uid, $update_data);

			Queue::insertQueue(
				'queue/Sysmsg/Send',
				[
					'msgCode' => 0,
					'to_uid' => $uid,
					'msgParams' => [
						'from_uid' => User::DEFAULT_HAOHAOZHU_UID,
						'title' => '',
						'detail' => '恭喜你！你的好好住帐号已成为「好好住认证设计师」。设计咨询功能已开通，快去登录好好住APP，开启你职业生涯的新篇章吧！期待你结识到欣赏你的屋主，尽情展现你的作品、生活与专业知识、经验。以后的日子里请多多关照喔：）',
					]
				], Queue::QUEUE_DORAEMON
			);

			$order_info = DesignerOrder::selectOrder($dsn);
			if ($auth_info['auth_status'] != DesignerAuth::STATUS_AUTH_COMPLETE &&
				$designer_type == DesignerAuth::DESIGNER_TYPE_COMPANY) {
				$url = Hhzurl::getDomain(). '/designer/organization-account-management/home';
				Queue::insertQueue('queue/Sysmsg/Send', [
					'msgCode' => 606,
					'to_uid' => $uid,
					'msgParams' => [
						'package_name' => $order_info['package_name'],
                        'link' => HhzNiceLivingUrl::getNormalH5Link($url)
					]
				], Queue::QUEUE_DORAEMON);
			}


			// 开发票下行
            /**   8.15号取消下行
			Queue::insertQueue(
				'queue/Sysmsg/Send',
				[
					'msgCode' => 0,
					'to_uid' => $uid,
					'msgParams' => [
						'from_uid' => User::DEFAULT_HAOHAOZHU_UID,
						'title' => '',
						'link' => HhzNiceLivingUrl::getNormalH5Link('http://yingzaojia.mikecrm.com/gXBPbeX'),
						'detail' => '如需开认证费发票，请点击此消息填写发票信息！您也可以加微信「haohaozhu0927」咨询开发票的进度哦～',
					]
				], Queue::QUEUE_DORAEMON
			);
             **/

			// 从子账号身份变更为非子账号的非测试号设计师，需要从黑名单中移出
			if ($designer_type != DesignerAuth::DESIGNER_TYPE_COMPANY_BYPASS && !$auth_info['is_test']) {
				$condition = [
					'type' => BlackList::TYPE_DESIGNER,
					'uid' => $uid,
					'data_status' => BlackList::STATUS_NORMAL,
				];
				$employee_black_record = BlackList::getByCondition($condition);

				if (!empty($employee_black_record)) {
					$data = [
						'data_status' => BlackList::STATUS_DELETE,
						'edit_time' => time()
					];
					$where = [
						'type' => BlackList::TYPE_DESIGNER,
						'uid' => $uid
					];
					BlackList::update($data, $where);
				}
			}

			Designer::updateDesigner($uid, [
				'designer_type' => $designer_type
			]);

			DesignerSearch::updateDesignerByUid($uid);
			DesignerEquityService::addEquity($uid, $order_info['package_id']);

			$admin_name = Admin::user()->username;
			$op_log = [
				'uid' => $uid,
				'reason' => '开通认证',
				'op' => Designer\DesignerOpLog::AUTH_PASSED,
				'op_time' => date('Y-m-d H:i:s'),
				'admin_id' => Admin::user()->id,
				'admin_name' => $admin_name
			];

			$id = Designer\DesignerOpLog::create($op_log);

			if ($id) {
				// 开认证成功的短信通知
				$phone = Phone::getUserPhone($uid);
				$decrypt_phone = PhoneCrypto::decrypt($phone, 'magic_mirror_decrypt_sms', PhoneCrypto::VERSIN);
				Sms::sendTplMsg($decrypt_phone, Sms::TYPE_DESIGNER_AUTH_COMPLETE);

				$msg = implode("\n", [
					"操作：开通认证服务",
					"设计师uid：{$uid}",
					"支付单号：{$dsn}",
					"操作人：{$admin_name}\n",
				]);
                DesignerDingTalkAlert::sendBeerusDesignerAuthAuditMsg2Operator($uid, $msg);


				// 发送认证礼包 NEED:停止推送By陈安阳
//				AuthService::sendAuthGift($uid);
			}

			$success = new MessageBag([
				'title' => '服务开通成功'
			]);

			return redirect('/admin/DesignerAuth/services/'. $uid)->with(compact('success'));
		} else {
			$error = new MessageBag([
				'title' => '服务开通失败，请稍后再试'
			]);

			return redirect('/admin/DesignerAuth/services/'. $uid)->with(compact('error'));
		}
	}
}
